# coding=utf-8
# 代码文件：client/ui/request_frame.py

"""用户登录窗口"""
import datetime
import wx
import wx.grid
import requests
from ui.my_frame import MyFrame
from ui.request_gridtable import RequestGridTable
from services.auth_service import AuthService


class RequestFrame(MyFrame):
    def __init__(self, request, file_list_frame):
        super().__init__(title='文档请求', size=(1000, 700))
        self.request = request
        self.file_list_frame = file_list_frame

        # 加载数据到 data
        self.data = self.loaddata()

        # 设置整个窗口布局是垂直 Box 布局
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.contentpanel.SetSizer(vbox)

        # 添加顶部对象（topbox）到 vbox
        vbox.Add(self.createtopbox(), 1, flag=wx.EXPAND | wx.ALL, border=10)
        # 添加底部对象（grid）到 vbox
        vbox.Add(self.creategrid(), 1, flag=wx.CENTER | wx.FIXED_MINSIZE | wx.ALL, border=10)

        # 为当前 Frame 对象添加默认状态栏
        self.CreateStatusBar()
        self.SetStatusText('准备就绪')

    def createtopbox(self):
        """创建顶部布局管理器 tipbox"""

        # 创建按钮对象
        return_btn = wx.Button(parent=self.contentpanel, label='返回文档列表')
        submit_btn = wx.Button(parent=self.contentpanel, label='提交请求')

        # 绑定事件处理
        self.Bind(wx.EVT_BUTTON, self.return_btn_onclick, return_btn)
        self.Bind(wx.EVT_BUTTON, self.submit_btn_onclick, submit_btn)

        box = wx.BoxSizer(wx.HORIZONTAL)
        box.AddSpacer(350)
        box.Add(return_btn, 1, flag=wx.EXPAND | wx.ALL, border=10)
        box.AddSpacer(20)
        box.Add(submit_btn, 1, flag=wx.EXPAND | wx.ALL, border=10)
        box.AddSpacer(350)

        return box

    def creategrid(self):
        """创建请求表格"""

        # 创建网格对象
        grid = wx.grid.Grid(self.contentpanel, name='grid')

        # 初始化表格
        # 创建网格中所需的表格
        table = RequestGridTable(self.data)
        # 设置网格的表格属性
        grid.SetTable(table, True)
        grid.SetSize(1000, 600)

        # 设置网格所有行高
        rowsizeinfo = wx.grid.GridSizesInfo(40, [])
        grid.SetRowSizes(rowsizeinfo)
        # 设置网格所有列宽
        colsizeinfo = wx.grid.GridSizesInfo(176, [])
        grid.SetColSizes(colsizeinfo)

        # 设置单元格默认字体
        grid.SetDefaultCellFont(wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                                        wx.FONTWEIGHT_NORMAL, faceName='微软雅黑'))
        # 设置行和列标题的默认字体
        grid.SetLabelFont(wx.Font(9, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                                  wx.FONTWEIGHT_NORMAL, faceName='微软雅黑'))
        # 设置网格选择模式为行选择
        grid.SetSelectionMode(grid.SelectRows)
        # 设置不能通过拖动改变行高度
        grid.DisableDragRowSize()
        # 设置不能通过拖动改变列高度
        grid.DisableDragColSize()

        return grid

    def loaddata(self):
        """根据请求中保存的文档 id 查询出商品的其他属性"""

        data = []
        for fileid in self.request.keys():
            try:
                file = AuthService.fetch_file_data(fileid)
                row = {
                    'fileid': file['fileid'],
                    'cname': file['cname'],
                    'points': file['points']
                }
                data.append(row)
            except Exception as e:
                print(e)

        return data

    def return_btn_onclick(self, event):
        """返回文档列表按钮事件处理"""

        # 更新请求
        for gridrowdata in self.data:
            fileid = gridrowdata['fileid']                   # 文档编号
            points = gridrowdata['points']                   # 文档点数
            self.request[fileid] = points

        self.file_list_frame.Show()
        self.Hide()

    def submit_btn_onclick(self, event):
        """提交请求按钮事件处理"""

        # 生成请求单
        self.generaterequests()

        dlg = wx.MessageDialog(self, '请求单已经生成', '信息', wx.YES_NO | wx.ICON_INFORMATION)

        if dlg.ShowModal() == wx.ID_YES:
            # TODO等待确认
            print('等待确认…')
            pass

        # 退出系统
        self.Destroy()
        dlg.Destroy()

    def generaterequests(self):
        """生成请求单"""
        requestdate = datetime.datetime.today()
        userid = MyFrame.Session['userid']
        requestid = int(requestdate.timestamp() * 1000)
        status = 0

        for row in self.data:
            request = {
                'request_id': requestid,
                'user_id': userid,
                'file_id': row['fileid'],
                'request_date': requestdate.isoformat(),
                'status': status,
                'points': row['points']
            }

            try:
                session_data = AuthService.load_session()
                short_jwt = session_data.get('short_jwt')
                AuthService.create_request(request, short_jwt)
            except Exception as e:
                print(e)
